import baseUrl from "./url.js"
const request = (url, data, method="POST", contentType="application/x-www-form-urlencoded") => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync("ai-token") || ''
		const httpDefaultOpts = {
			url: baseUrl.url + url,
			data,
			method,
			dataType: "json",
			withCredentials: true,
			header: {
				"x-requested-with": "XMLHttpRequest",
				"content-type": contentType,
				"aiettoken": token,
			}
		} 
		uni.request(httpDefaultOpts).then(res => {
			console.log(res)
			if (res.statusCode === 200) {
				console.log(res)
				if(res.data.code === 200) {  //请求成功
					resolve(res.data)
				} else if (res.data.code === 500 && res.data.msg === "token无效") {  //token失效
					resolve(res.data)
					uni.removeStorageSync("ai-token")						
				} else {
					console.log("发生错误的URL", url, data)
					resolve(res.data)
				}
			} else {
				console.log("发生错误的URL", url, data)
				reject(res)
			}
		}).catch((response) => {
			reject(response)			
		})
	})
}

export default request